import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'ServiceLocator.dart';
import 'TelAndSmsService.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:vehicle_management/config/Config.dart';
import 'package:vehicle_management/utils/bottom_dialog.dart';

// ignore: unused_element
TelAndSmsService _service = locator<TelAndSmsService>();
List driverName = [];
List latereasonsList = [];
List userId = [];
//加载中的圈圈
Widget getMoreWidget(hasMore) {
  if (hasMore) {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 2.0,
            )
          ],
        ),
      ),
    );
  } else {
    return Center(
      child: Text("--我是有底线的--"),
    );
  }
}

/**
 *列表中中的数据
 *
 */
tranisitIng(List list, index, hasmore, context, String appKey) {
  /**
   * 分割司机名称跟电话
   * @param driverName : 司机名称
   */
  if (list[index]['driverNames'] != null && list[index]['driverNames'] != '') {
    driverName = list[index]['driverNames'].split(',');
  }
  // ignore: missing_return
  getTelphone(telphone) {
    RegExp phoneReg = new RegExp(r'(?<=\()\d+');
    Iterable<Match> phoneMatches = phoneReg.allMatches(telphone);
    for (Match m in phoneMatches) {
      return m.group(0);
    }
  }
  /**
   *  判断一下是否为司机
   * @param    userId[2] :3  司机端
   */
  Uint8List base64deBody = base64Decode(appKey);
  String decryptText = Utf8Decoder().convert(base64deBody);
  // ignore: unused_local_variable
  if (decryptText != null) {
    userId = decryptText.split('~');
  }
  //空白
  Widget blankContent() {
    return Container(
      color: Colors.red,
      child: SizedBox(
        height: ScreenUtil().setHeight(5),
      ),
    );
  }
  // 延误原因按钮  确认收货按钮
  Widget driverButton() {
    List<Widget> buttons = [];
    Widget content;
    buttons.add(new Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Container(
          height: ScreenUtil().setHeight(58),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          alignment: Alignment.center,
          child: RaisedButton(
              color: Color(0xffFB5858),
              textColor: Colors.white,
              child: Text(
                "延误原因",
                style: TextStyle(fontSize: ScreenUtil().setSp(30)),
              ),
              onPressed: () async {
                var apiUrl = "${Config.latereasonsUrl}?appKey=$appKey";
                var response = await Dio().get(apiUrl);
                latereasonsList = (response.data)['data'];
                showDialog(
                    barrierDismissible: true, //是否点击空白区域关闭对话框,默认为true，可以关闭
                    context: context,
                    builder: (BuildContext context) {
                      return BottomSheetWidget(
                          list: latereasonsList,
                          onItemClickListener: (reasonIndex) async {
                            var taskId = list[index]['id'];
                            var reason = latereasonsList[reasonIndex];
                            var apiUrl =
                                "${Config.reportreasonUrl}?appKey=$appKey&taskId=$taskId&reason=$reason";
                            print(apiUrl);
                            var response = await Dio().get(apiUrl);
                            print(response);
                            Navigator.of(context).pushReplacementNamed('/Home');
                          });
                    });
              }),
        ),
        SizedBox(
          width: ScreenUtil().setWidth(50),
        ),
        Container(
          height: ScreenUtil().setHeight(58),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          alignment: Alignment.center,
          child: RaisedButton(
              color: Color(0xffFB5858),
              textColor: Colors.white,
              child: Text(
                "确认收货",
                style: TextStyle(fontSize: ScreenUtil().setSp(30)),
              ),
              onPressed: () async {
                FormData formData = FormData.fromMap({
                  "taskId": list[index]['id'],
                });
                print(list[index]['id']);
                var apiUrl = "${Config.doarrivalUrl}?appKey=$appKey";
                await Dio().post(apiUrl, data: formData);
                Navigator.of(context).pushReplacementNamed('/Home');
              }),
        )
      ],
    ));
    content =
        new Row(mainAxisAlignment: MainAxisAlignment.end, children: buttons);
    return content;
  }
  //司机名字拆分组件
  Widget buildGrid() {
    List<Widget> tiles = []; //先建一个数组用于存放循环生成的widget
    Widget content; //单独一个widget组件，用于返回需要生成的内容widget
    for (var item in driverName) {
      tiles.add(new Row(children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(345),
          child: Text(
            item ?? '暂无',
            style: TextStyle(
              fontSize: ScreenUtil().setSp(30),
              color: Color(0xfff0E0E0E),
            ),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            IconButton(
              icon: Icon(
                Icons.phone,
                color: Colors.red,
              ),
              onPressed: () => _service.call(getTelphone(item)),
            )
          ],
        ),
      ]));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }
  // ignore: non_constant_identifier_names
  Widget ExampleWidget = buildGrid();
  Widget dirverWidget = driverButton();
  Widget blankWidget = blankContent();
  Widget transitIngItemList() {
    List<Widget> buttons = [];
    Widget content;
    buttons.add(Column(
      children: <Widget>[
        ///起点 终点  和轨迹 Row排列方便
        Container(
          decoration: BoxDecoration(color: Colors.white, boxShadow: <BoxShadow>[
            BoxShadow(
              color: Colors.grey[400],
            ),
          ]),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                  flex: 3,
                  child: Container(
                    color: Color(0xFFFEFEFE),
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                      child: Column(
                        children: <Widget>[
                          ///起点
                          Row(
                            children: <Widget>[
                              Image.asset('images/startPlace.png'),
                              Container(
                                width: ScreenUtil().setWidth(400),
                                margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: Text(
                                  list[index]['fromAddress'],
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: Color(0xff0E0E0E),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            height: ScreenUtil().setHeight(50),
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil().setHeight(20), 0, 0, 0),
                            decoration: BoxDecoration(
                              border: Border(
                                  left: BorderSide(
                                      color: Colors.grey[200],
                                      width: 1,
                                      style: BorderStyle.solid)),
                            ),
                          ),

                          ///终点
                          Row(
                            children: <Widget>[
                              Image.asset('images/endPlace.png'),
                              Container(
                                width: ScreenUtil().setWidth(400),
                                margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: Text(
                                  list[index]['toAddress'],
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: Color(0xff0E0E0E),
                                  ),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  )),
              Expanded(
                child: Container(
                  width: ScreenUtil().setWidth(120),
                  color: Color.fromRGBO(255, 255, 255, 0.8),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset('images/transitLine.png'),
                      FlatButton(
                          child: Text(
                            "查看位置",
                            style: TextStyle(
                              color: Color(0xffFB5858),
                              fontSize: ScreenUtil().setSp(30),
                            ),
                          ),
                          onPressed: () {
                            //传递车辆信息
                            Navigator.pushNamed(context, '/TrajectoryMapPage',
                                arguments: {'datas': list[index]});
                          })
                    ],
                  ),
                ),
              )
            ],
          ),
        ),

        ///联系人电话
        Container(
          decoration: BoxDecoration(color: Colors.white, boxShadow: <BoxShadow>[
            BoxShadow(
              color: Colors.grey[400],
            ),
          ]),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              //涉及到widget的大小或者边框的时候，使用container包裹
              Container(
                child: Row(
                  children: <Widget>[
                    /// 车牌号
                    Container(
                      alignment: Alignment.center,
                      color: Color(0xfff2f2f2),
                      padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
                      margin: EdgeInsets.fromLTRB(20, 0, 10, 0),
                      child: Text(
                        list[index]['vehicleNo'] ?? '暂无',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(30),
                          color: Color(0xff0E0E0E),
                        ),
                      ),
                    ),

                    Container(
                      child: ExampleWidget,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(
          padding: userId[2] == '3'
              ? EdgeInsets.fromLTRB(0, 10, 20, 10)
              : EdgeInsets.fromLTRB(0, 0, 0, 0),
          decoration: BoxDecoration(color: Colors.white, boxShadow: <BoxShadow>[
            BoxShadow(
              color: Colors.grey[400],
            ),
          ]),
          child: userId[2] == '3' ? dirverWidget : blankWidget,
        ),
        //延迟原因
        Container(
          padding: (userId[2] == '3' && list[index]['lateReason'] != null)
              ? EdgeInsets.fromLTRB(20, 10, 20, 10)
              : EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: userId[2] == '3'
              ? Row(
                  children: <Widget>[
                    Text(list[index]['lateReason'] == null ? '' : '延迟原因：'),
                    SizedBox(
                      width: ScreenUtil().setWidth(5),
                    ),
                    Text(
                      list[index]['lateReason'] != null
                          ? list[index]['lateReason']
                          : '',
                      style: TextStyle(
                          color: Colors.red, fontWeight: FontWeight.bold),
                    )
                  ],
                )
              : blankWidget,
        ),
        SizedBox(
          height: ScreenUtil().setHeight(20),
        ),
        (index == list.length - 1) ? Divider() : blankWidget,
        index == list.length - 1 ? getMoreWidget(hasmore) : blankWidget,
      ],
    ));
    content = new Column(children: buttons);
    return content;
  }
  Widget transitIngItem = transitIngItemList();
  ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
  if (index == list.length - 1) {
    return Container(
      child: transitIngItem,
    );
  } else {
    return Container(
      child: transitIngItem,
    );
  }
}
